<template>
	<view>
		<u-notify ref="uNotify" message="Hi uView"></u-notify>
		<u-toast ref="uToast"></u-toast>
		<u-modal :show="show" @confirm="confirm">
			<view class="slot-content">
				<input type="text" placeholder="请输入用户名" v-model="user">
			</view>
		</u-modal>
		<!-- 聊天区域 -->
	<view>
		<view class="ul">
			<view v-for="(item,index) in allMsg" >
				<template v-if="item.type===1">
					<view>{{item.date}} {{item.username}}</view>
					<view>{{item.msg}}</view>
				</template>
				<template v-else>
					<view>{{item.msg}}</view>
				</template>
			</view>
		</view>
	</view>
		<!-- 发信息 -->
		<view>
			<input type="text" placeholder="" v-model="information">
			<button @click="send">发送</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				user: "",
				show: true,
				userId:"",
				information:'',
				allMsg:[]
			}
		},
		methods: {
			confirm() {
				this.user = this.user.trim()
				if (!this.user.length) {
					this.show = false
					this.$refs.uNotify.show({
						top: 10,
						type: 'error',
						color: '#000',
						bgColor: '#e8e8e8',
						message: 'Hi uView',
						duration: 1000 * 3,
						fontSize: 20,
						safeAreaInsetTop: true
					})
					setTimeout(() => {
						this.show = true
					}, 1000)
				} else {
					//链接 socket
					this.linkSocket()
				}
			},

			linkSocket() {
				uni.connectSocket({
					url: 'ws://10.18.5.125:7890'
				})
				//监听socket是否连接成功
				uni.onSocketOpen(()=> {
					this.show = false
					this.$refs.uToast.show({
						type:'success',
						message:"websocket连接成功"
					})
					//持久化用户名和用户id
					let setUser=uni.setStorageSync("userId",this.userId)
					let setUserId=uni.setStorageSync("user",this.user)
					if(!setUser&&!setUserId){
						this.userId='abc'+(new Date()).getTime()
						uni.setStorageSync("user",this.user)
						uni.setStorageSync("userId",this.userId)
						this.sendMessage(2)
					}
					//监听scoket消息分发
					uni.onSocketMessage((data)=>{
						this.allMsg.push(JSON.parse(data.data))
					})
					
				})
			},
			send(){
				this.sendMessage(1,this.information)
			},
			sendMessage(type,msg){
				//向socket发送信息
				uni.sendSocketMessage({
					data:JSON.stringify({
						type,msg,
						username:this.user,
						userid:this.userId
					})
				})
				
			}
		},
		onShow(){
			let setUser=uni.setStorageSync("userId",this.userId)
			let setUserId=uni.setStorageSync("user",this.user)
			if(setUser&&setUserId){
				this.show=false
				this.linkSocket()
			}else{
				this.show=true
			}
		},
		onHide(){
			console.log('chat隐藏了')
			uni.closeSocket({
				
			})
		}
	}
</script>

<style>

</style>
